
//  hx_test.swift
//  Runner
//
//  Created by 123456 on 2023/6/16.


import Foundation
import Flutter
import UIKit
import HelpDesk
import Hyphenate


public class HxDemoPlugin: NSObject, FlutterPlugin{
    
    

    
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "hx_demo", binaryMessenger: registrar.messenger())
    let instance = HxDemoPlugin()
    HxChatManage.shared.register(registrar: registrar);
    registrar.addMethodCallDelegate(instance, channel: channel)
  }
    

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        //    result("iOS " + UIDevice.current.systemVersion)

        switch call.method {
            
        case "init":
            initMethod(call: call, result: result)
            break;
        case "register":
            registerMethod(call: call, result: result)
            break;
        case "login":
            loginMethod(call: call, result: result)
            break;
        case "isLogin":
            isLoginMethod(call: call, result: result)
            break;
        case "logout":
            logoutMethod(call: call, result: result)
            break;
        case "sendTextMessage":
            sendTextMeesage(call: call, result: result)
            break;
        case "getMessages":
            getMessages(call: call, result: result)
            break;
            
        default:
            return
        }
        

    }


    public func initMethod(call: FlutterMethodCall, result: @escaping FlutterResult){
        let option = HDOptions()
        let arguments = call.arguments  as! [String:Any]
        option.appkey = arguments["appKey"] as? String
        option.tenantId = arguments["tenantId"] as? String
        let error =  HDClient.shared().initializeSDK(with: option)
        guard error == nil else{
            result(error?.errorDescription)
            return
        }
        result("success")
        HxChatManage.shared.setEventMessage()

    }

    public func registerMethod(call: FlutterMethodCall, result: @escaping FlutterResult){
        let arguments = call.arguments  as! [String:Any]
        let username = arguments["username"] as? String
        let password = arguments["password"] as? String
        let error =  HDClient.shared().register(withUsername: username, password: password)
        guard error == nil else{
            result(error?.errorDescription)
            return
        }
        result("success")
        

    }

    public func loginMethod(call: FlutterMethodCall, result: @escaping FlutterResult){
        let arguments = call.arguments  as! [String:Any]
        let username = arguments["username"] as? String
        let password = arguments["password"] as? String
        let error = HDClient.shared().login(withUsername: username, password: password)
        guard error == nil else{
            result(error?.errorDescription)
            return
        }
        result("success")
        
    }

    public func isLoginMethod(call: FlutterMethodCall, result: @escaping FlutterResult){

        if(HDClient.shared().isLoggedInBefore){
            result(NSNumber(value: true))
        }else{
            result(NSNumber(value: true))
        }
    }

    public func logoutMethod(call: FlutterMethodCall, result: @escaping FlutterResult){

        let error = HDClient.shared().logout(true)
        guard error == nil else{
            result(error?.errorDescription)
            return
        }
        result("success")
        
    }
    
}





///获取消息
extension HxDemoPlugin {
    
    public func sendTextMeesage(call: FlutterMethodCall, result: @escaping FlutterResult){
        
        let arguments = call.arguments  as! [String:Any]
        let text = arguments["text"] as? String
        let toUser = arguments["toUser"] as? String
        let message = HDMessage.createTxtSend(withContent: text, to: toUser)
        HDClient.shared().chatManager.send(message) { progress in
            //发送消息进度
            print(progress)
           
        } completion: { [self] (aMessages, aError) in
            //发送消息完成，aError为空则为发送成功
            print(aError as Any)
            if let error = aError {
                // 处理错误
                result(error.errorDescription)
            } else if let messages = aMessages {
                // 获取到消息 messages
                result(messageToDict(message: message!))
            }
        }

    }
    
    public func getMessages(call: FlutterMethodCall, result: @escaping FlutterResult){
        
        let arguments = call.arguments  as! [String:Any]
        let aMessageId = arguments["messageId"] as? String ?? ""
        let serviceNumber = arguments["serviceNumber"] as? String
        let count = arguments["count"] as? Int32 ?? 20
 
        let conversation = HDClient.shared().chatManager.getConversation(serviceNumber)
        conversation!.loadMessagesStart(
            fromId: aMessageId == "" ? nil : aMessageId,
            count: count,
            searchDirection: HDMessageSearchDirectionUp){[self] (aMessages, aError) in
                
                if let error = aError {
                // 处理错误
                    result(error.errorDescription)
                } else if let messages = aMessages, !messages.isEmpty {
                // 获取到消息 messages
                var msgs:[Any] = [];
                messages.forEach { message in
                    msgs.append(messageToDict(message: message as! HDMessage));
                }
                result(msgs)
            }
        }
    }
    
    func handleParameter(_ parameter: String) -> String? {
        return parameter == "" ? nil : parameter
    }
    
    
    
    
    
    func messageToDict(message: HDMessage) -> [String: Any]{
        
        ///消息json
        var messageData = [String: Any]()
        
        messageData["messageId"] = message.messageId
        messageData["conversationId"] = message.conversationId
        messageData["direction"] = message.direction.rawValue
        messageData["from"] = message.from
        messageData["to"] = message.to
        messageData["timestamp"] = message.messageTime
        messageData["status"] = message.status.rawValue
        messageData["body"] = messageBody(body: message.body)
        messageData["ext"] = message.ext

        return messageData
    }
    
    //    EMMessageBodyTypeText   = 1,    /*! \~chinese 文本类型 \~english Text */
    //    EMMessageBodyTypeImage,         /*! \~chinese 图片类型 \~english Image */
    //    EMMessageBodyTypeVideo,         /*! \~chinese 视频类型 \~english Video */
    //    EMMessageBodyTypeLocation,      /*! \~chinese 位置类型 \~english Location */
    //    EMMessageBodyTypeVoice,         /*! \~chinese 语音类型 \~english Voice */
    //    EMMessageBodyTypeFile,          /*! \~chinese 文件类型 \~english File */
    //    EMMessageBodyTypeCmd,           /*! \~chinese 命令类型 \~english Command */
    //    EMMessageBodyTypeCustom,        /*! \~chinese 自定义类型 \~english Custom */
    
    ///消息body
    func messageBody(body: EMMessageBody) -> Dictionary<String, Any>{
        
        var messagebody = [String: Any]()
        //文字消息
        if body is EMTextMessageBody {
            let textMsg:EMTextMessageBody = body as! EMTextMessageBody
            messagebody["text"] = textMsg.text
            
            switch textMsg.type.rawValue {
            case 1:
                messagebody["type"] = "txt"
            default:
                messagebody["type"] = "other"
            }
        
        }
        //视频消息
        else if body is EMVideoMessageBody {
            
        }
        //图片消息
        else if body is EMImageMessageBody {
            
        }
        //文件消息
        else if body is EMFileMessageBody {
            
        }
        //自定义消息
        else if body is EMCustomMessageBody {
            
        }
        ///其它消息（语音<VOICE>，命令<CMD>,位置<LOCATION>）
        else {
            
        }
        
        return messagebody
 
    }
    
}
